import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from "@nestjs/common";
import * as dayjs from 'dayjs';
import { Response, Request } from 'express';

@Catch()
export class GlobalErrorFilter implements ExceptionFilter {
    catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const request = ctx.getRequest<Request>();
        const status = exception instanceof HttpException ? exception.getStatus() : 500;
        // 以统一的JSON格式返回错误信息
        let message: any = exception || "系统错误"
        if (exception instanceof Error) {
            message = exception.message;
        }
        response
            .status(status)
            .json({
                code: status,
                message,
                data: null,
                timestamp: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                path: request.url,
            });
    }
}